import { defineStore } from "pinia";
import * as authApi from "@/api/auth";
import * as userApi from "@/api/user";
import * as tenantApi from "@/api/tenant";
import router from "@/router";

const isExpired = (expiresTime: number) => expiresTime < Date.now() - 1000 * 60;

export const useUserStore = defineStore("user", {
  persist: {
    paths: ["auth", "userInfo", "tenantInfo", "shareInfo"],
  },
  state: () => ({
    auth: {
      userId: "0",
      accessToken: "",
      refreshToken: "",
      expiresTime: 0,
    } as AuthData,
    // 通过分享链接/二维码进入的信息，生命周期只有单次访问，不会持久化存储
    shareInfo: {
      /**
       * 分享者id
       * 写入途径：1、跳转登录页前。2、在App.vue中
       * 用途：1、用户登录时，作为邀请者id传入。2、用户下单时，作为签单人传入。
       */
      userId: null,
      // 在跳转登录页面前写入，在登录成功后跳转
      targetPath: "/",
    } as ShareInfo,
    // 在用户登录后写入
    userInfo: null as UserInfo | null,
    // 跳转登录前写入
    tenantInfo: null as TenantInfo | null,
  }),

  getters: {},

  actions: {
    // 跳转到登陆页面
    async gotoLogin() {
      const route = router.currentRoute.value;

      this.updateTenantInfo();

      // 记录当前路径，一边登录成功后返回
      const { path } = route;
      this.shareInfo.targetPath = path;

      // 记录分享者id
      const uid = route.query.uid as string;
      uid && (this.shareInfo.userId = uid);

      // 跳转到登录页面
      router.replace("/login");
    },

    async updateTenantInfo() {
      const { data: tenantInfo } = await tenantApi.getTenantInfo();
      this.tenantInfo = tenantInfo;
    },

    async updateUser() {
      const { data: userInfo } = await userApi.getUserInfo();
      this.userInfo = userInfo;
    },

    async resetAuth() {
      this.auth.accessToken = "";
      this.auth.refreshToken = "";
      this.auth.expiresTime = 0;
      await this.checkLocalAuth();
    },

    async updateAuth(data: LoginResult) {
      this.auth.accessToken = data.accessToken;
      this.auth.refreshToken = data.refreshToken;
      this.auth.expiresTime = data.expiresTime;
      this.auth.userId = data.userId;
      await this.updateUser();
    },

    async refreshAuthByToken(token: AuthData["accessToken"]) {
      const { data } = await authApi.getTokenData(token);
      this.updateAuth(data);
    },

    /** 登录 */
    async login(params: LoginForm) {
      const { data } = await authApi.login(params);
      this.updateAuth(data);
    },

    /** 刷新token */
    async refreshToken() {
      const { data } = await authApi.refresh(this.auth.refreshToken);
      this.updateAuth(data);
    },

    /** 检查本地认证 */
    async checkLocalAuth() {
      const { auth, refreshToken } = this;

      // 登录
      if (!auth.accessToken) {
        await this.gotoLogin();
        throw new Error("未登录");
      }

      // 刷新token
      if (isExpired(auth.expiresTime)) {
        console.log("刷新token");
        try {
          await refreshToken();
        } catch (e) {
          await this.gotoLogin();
          throw new Error("刷新token失败");
        }
      }
    },

    /** 更新分享者id */
    updateShareUserId(userId: string){
      this.shareInfo.userId = userId;
    }
  },
});
